from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,redirect
from django.urls import reverse
from .. import models
import time,os
from shop.settings import BASE_DIR


def tab():
    cates = models.Cates.objects.extra(select = {'newpath':'concat(paths,id)'}).order_by('newpath')
    for i in cates:
        num = i.paths.count(',')-1
        i.newname=num*'|----'
    return cates  

def addcate(request):
    if request.method=='GET':
        # 将所有的类型返回
		# cates = models.Cates.objects.all()
	    # cates = models.Cates.objects.extra(select = {'newpath':'concat(paths,id)'}).order_by('newpath')
	    # for i in cates:
	    #     num = i.paths.count(',')-1
	    #     i.newname=num*'|----'
        cates = tab()

        return render(request,'myadmin/cate/addcate.html',{'cates':cates})
    elif request.method=='POST':
        # 接受pid 通过pid来判断是不是顶级分类
        pid = request.POST.get('pid')
        name = request.POST.get('name')
        # print(pid)
        # print(name)
        if pid=='0':
            cate = models.Cates()
            cate.name=name
            cate.upid=int(pid)
            cate.paths='0,'
            cate.save()
        else:
            # 根据pid找父级 paths
            pobj = models.Cates.objects.get(id=pid)
            c = models.Cates()
            c.name=name
            c.upid=pobj.id
            c.paths=pobj.paths+pid+','
            c.save()
           
            
        # 接受数据添加数据
        return HttpResponse('添加成功')


def catelist(request):
    # 查询所有的分类
    # cates = models.Cates.objects.all()
    # select *,concat(paths,id) as newpath  from myadmin_cates order by newpath;
    # 模型提供 extra
    # cates = models.Cates.objects.extra(select = {'newpath':'concat(paths,id)'}).order_by('newpath')

    # for i in cates:
    #     num = i.paths.count(',')-1
    #     i.newname=num*'|----'
    cates = tab()

    return render(request,'myadmin/cate/catelist.html',{'cates':cates})



def delcate(request):
    # 接受id 删除数据的id
    pid = int(request.GET.get('pid'))
    # 判断有没有子分类
    cnum = models.Cates.objects.filter(upid=pid).count()
    print(cnum)
    if cnum:
        return JsonResponse({'msg':0})
    else:
        c = models.Cates.objects.get(id=pid)
        c.delete()
        return JsonResponse({'msg':1})

# 修改
def editcate(request):
    # 接受id和name
    cid = int(request.GET.get('id'))
    cname = request.GET.get('name')
    try:
        cate = models.Cates.objects.get(id=cid)
        cate.name=cname
        cate.save()
        return JsonResponse({'msg':1})
    except :
        return JsonResponse({'msg':0})